package com.savi.myapplication.fragment;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.savi.myapplication.R;
import com.savi.myapplication.model.FlyCardAirdrop;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AirdropCardFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AirdropCardFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    static String pdfFilePath = null;
    // 初始化其他EditText
    private EditText date1;
    private EditText task_type1;
    private EditText aircraft1;
    private EditText captain1;
    private EditText airdrop_area1;
    private EditText platform_type1;
    private EditText platform_id1;
    private EditText send_type1;
    private EditText weight1;
    private EditText unit_weight1;
    private EditText height1;
    private EditText pressure_high1;
    private EditText send_speed1;
    private EditText send_ground_speed1;
    private EditText direction1;
    private EditText resultant_wind1;
    private EditText range1;
    private EditText horizontal_correction_amount1;
    private EditText vertical_correction_amount1;
    private EditText airdrop_time1;
    private EditText horizontal_actual_quantity1;
    private EditText vertical_actual_quantity1;
    private EditText airdrop_height1;
    private EditText airdrop_synthetic_wind1;
    private EditText plan_landing_time1;
    private EditText true_landing_time1;
    private EditText opening_time1;
    private EditText landing_time1;
    private EditText central_latitude_and_longitude1;
    private EditText ground_latitude_and_longitude1;
    private EditText landing_position1;
    private EditText diameter_difference1;
    private EditText departure_time1;
    private EditText falling_time1;
    private EditText invest_time1;
    private EditText correction_data1;
    private EditText continuous_investment_leader1;
    private EditText move_distance1;
    private EditText umbrella_range1;
    private EditText windless_range1;
    private EditText true_range1;
    private EditText decline_rate1;
    private EditText loss_height1;
    private Button buttonGeneratePDF;
    RecyclerView mRecyclerView;
    List<FlyCardAirdrop> mNewsList = new ArrayList<>();
    Button mButton;
    ArrayList<FlyCardAirdrop> list = new ArrayList<>();
    FlyCardAirdrop flyCardAirdrop = new FlyCardAirdrop();
    int currentIndex = 0; // 当前显示的索引

    MyAdapter mMyAdapter;
    public AirdropCardFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FuelCardFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AirdropCardFragment newInstance(String param1, String param2) {
        AirdropCardFragment fragment = new AirdropCardFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_airdrop, container, false);
        mRecyclerView = view.findViewById(R.id.recycleView);
        buttonGeneratePDF = view.findViewById(R.id.buttonGeneratePDF);
        mButton = view.findViewById(R.id.button);
        // 构造一些数据,假设最多10
        for (int i = 0; i < 10; i++) {
            FlyCardAirdrop item = new FlyCardAirdrop();
            mNewsList.add(item);
        }

        mMyAdapter = new MyAdapter(new ArrayList<>());
        mRecyclerView.setAdapter(mMyAdapter);
        // 初始显示的数据
        mMyAdapter = new MyAdapter(new ArrayList<>());
        mRecyclerView.setAdapter(mMyAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(layoutManager);

        // 添加第一个数据项
        if (!mNewsList.isEmpty()) {
            mMyAdapter.addData(mNewsList.get(currentIndex));
            currentIndex++;
        }

        // 设置按钮点击事件
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentIndex < mNewsList.size()) {
                    // 添加下一个数据项
                    mMyAdapter.addData(mNewsList.get(currentIndex));
                    currentIndex++; // 更新索引
                    mRecyclerView.scrollToPosition(mMyAdapter.getItemCount() - 1); // 滚动到最后一项
                }
                else{
                    //提示最多添加20条
                    Toast.makeText(getContext(), "最多添加 10 条数据", Toast.LENGTH_SHORT).show();
                }
            }
        });

        buttonGeneratePDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // 传入Fragment的context
                    generateTempPDF(getContext());
                    Toast.makeText(getContext(), "PDF生成成功！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 初始化预览按钮
        Button buttonPreviewPDF = view.findViewById(R.id.buttonPreviewPDF);
        buttonPreviewPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用预览PDF的方法
                previewPDF(getContext(),pdfFilePath);
            }
        });

        return view;
    }

    public Map<String, String> data() {
        Map<String, String> data = new HashMap<String, String>();
        //key要与模板中的别名一一对应
        for(int i = 0; i<currentIndex;i++) {
            View view=mRecyclerView.getLayoutManager().findViewByPosition(i);
            if(view!=null){
                date1 = view.findViewById(R.id.date1);
                task_type1 = view.findViewById(R.id.task_type1);
                aircraft1 = view.findViewById(R.id.aircraft1);
                captain1 = view.findViewById(R.id.captain1);
                airdrop_area1 = view.findViewById(R.id.airdrop_area1);
                platform_type1 = view.findViewById(R.id.platform_type1);
                platform_id1 = view.findViewById(R.id.platform_id1);
                send_type1 = view.findViewById(R.id.send_type1);
                weight1 = view.findViewById(R.id.weight1);
                unit_weight1 = view.findViewById(R.id.unit_weight1);
                height1 = view.findViewById(R.id.height1);
                pressure_high1 = view.findViewById(R.id.pressure_high1);
                send_speed1 = view.findViewById(R.id.send_speed1);
                send_ground_speed1 = view.findViewById(R.id.send_ground_speed1);
                direction1 = view.findViewById(R.id.direction1);
                resultant_wind1 = view.findViewById(R.id.resultant_wind1);
                range1 = view.findViewById(R.id.range1);
                horizontal_correction_amount1 = view.findViewById(R.id.horizontal_correction_amount1);
                vertical_correction_amount1 = view.findViewById(R.id.vertical_correction_amount1);
                airdrop_time1 = view.findViewById(R.id.airdrop_time1);
                horizontal_actual_quantity1 = view.findViewById(R.id.horizontal_actual_quantity1);
                vertical_actual_quantity1 = view.findViewById(R.id.vertical_actual_quantity1);
                airdrop_height1 = view.findViewById(R.id.airdrop_height1);
                airdrop_synthetic_wind1 = view.findViewById(R.id.airdrop_synthetic_wind1);
                plan_landing_time1 = view.findViewById(R.id.plan_landing_time1);
                true_landing_time1 = view.findViewById(R.id.true_landing_time1);
                opening_time1 = view.findViewById(R.id.opening_time1);
                landing_time1 = view.findViewById(R.id.landing_time1);
                central_latitude_and_longitude1 = view.findViewById(R.id.central_latitude_and_longitude1);
                ground_latitude_and_longitude1 = view.findViewById(R.id.ground_latitude_and_longitude1);
                landing_position1 = view.findViewById(R.id.landing_position1);
                diameter_difference1 = view.findViewById(R.id.diameter_difference1);
                departure_time1 = view.findViewById(R.id.departure_time1);
                falling_time1 = view.findViewById(R.id.falling_time1);
                invest_time1 = view.findViewById(R.id.invest_time1);
                correction_data1 = view.findViewById(R.id.correction_data1);
                continuous_investment_leader1 = view.findViewById(R.id.continuous_investment_leader1);
                move_distance1 = view.findViewById(R.id.move_distance1);
                umbrella_range1 = view.findViewById(R.id.umbrella_range1);
                windless_range1 = view.findViewById(R.id.windless_range1);
                true_range1 = view.findViewById(R.id.true_range1);
                decline_rate1 = view.findViewById(R.id.decline_rate1);
                loss_height1 = view.findViewById(R.id.loss_height1);
            data.put("date"+(i+1), date1.getText().toString());
            data.put("task_type"+(i+1),task_type1.getText().toString());
            data.put("aircraft"+(i+1), aircraft1.getText().toString());
            data.put("captain"+(i+1), captain1.getText().toString());
            data.put("airdrop_area"+(i+1), airdrop_area1.getText().toString());
            data.put("platform_type"+(i+1), platform_type1.getText().toString());
            data.put("platform_id"+(i+1), platform_id1.getText().toString());
            data.put("send_type"+(i+1), send_type1.getText().toString());
            data.put("weight"+(i+1), weight1.getText().toString());
            data.put("unit_weight"+(i+1),unit_weight1.getText().toString());
            data.put("height"+(i+1), height1.getText().toString());
            data.put("pressure_high"+(i+1), pressure_high1.getText().toString());
            data.put("send_speed"+(i+1), send_speed1.getText().toString());
            data.put("send_ground_speed"+(i+1), send_ground_speed1.getText().toString());
            data.put("direction"+(i+1), direction1.getText().toString());
            data.put("resultant_wind"+(i+1), resultant_wind1.getText().toString());
            data.put("range"+(i+1), range1.getText().toString());
            data.put("horizontal_correction_amount"+(i+1),horizontal_correction_amount1.getText().toString());
            data.put("vertical_correction_amount"+(i+1), vertical_correction_amount1.getText().toString());
            data.put("airdrop_time"+(i+1), airdrop_time1.getText().toString());
            data.put("horizontal_actual_quantity"+(i+1), horizontal_actual_quantity1.getText().toString());
            data.put("vertical_actual_quantity"+(i+1), vertical_actual_quantity1.getText().toString());
            data.put("airdrop_height"+(i+1), airdrop_height1.getText().toString());
            data.put("airdrop_synthetic_wind"+(i+1), airdrop_synthetic_wind1.getText().toString());
            data.put("plan_landing_time"+(i+1), plan_landing_time1.getText().toString());
            data.put("true_landing_time"+(i+1),true_landing_time1.getText().toString());
            data.put("opening_time"+(i+1), opening_time1.getText().toString());
            data.put("landing_time"+(i+1), landing_time1.getText().toString());
            data.put("central_latitude_and_longitude"+(i+1), central_latitude_and_longitude1.getText().toString());
            data.put("ground_latitude_and_longitude"+(i+1), ground_latitude_and_longitude1.getText().toString());
            data.put("landing_position"+(i+1), landing_position1.getText().toString());
            data.put("diameter_difference"+(i+1), diameter_difference1.getText().toString());
            data.put("departure_time"+(i+1), departure_time1.getText().toString());
            data.put("falling_time"+(i+1),falling_time1.getText().toString());
            data.put("invest_time"+(i+1), invest_time1.getText().toString());
            data.put("correction_data"+(i+1), correction_data1.getText().toString());
            data.put("continuous_investment_leader"+(i+1), continuous_investment_leader1.getText().toString());
            data.put("move_distance"+(i+1), move_distance1.getText().toString());
            data.put("umbrella_range"+(i+1), umbrella_range1.getText().toString());
            data.put("windless_range"+(i+1), windless_range1.getText().toString());
            data.put("true_range"+(i+1), true_range1.getText().toString());
            data.put("decline_rate"+(i+1),decline_rate1.getText().toString());
            data.put("loss_height"+(i+1), loss_height1.getText().toString());
            }

        }
        return data;
    }

    // 修改generateTempPDF方法签名，传入Context
    public String generateTempPDF(Context context) throws Exception {
        PdfReader reader = null;
        PdfStamper ps = null;
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        InputStream is = null;
        try {
            // 获取外部存储的根目录
            File externalStorage = Environment.getExternalStorageDirectory();

            // 构建具体的文件路径
            File file = new File(externalStorage, "MFBdata/Template/AirdropTemplatePDF.pdf");

            // 检查文件是否存在
            if (file.exists()) {
                // 如果文件存在，使用 FileInputStream 读取文件
                is = new FileInputStream(file);
                Log.d("FileSuccess", "模板文件已找到: " + file.getAbsolutePath());
            } else {
                // 如果文件不存在，提示未发现模板文件
                Log.e("FileError", "未发现模板文件: " + file.getAbsolutePath());
                Toast.makeText(context, "未发现模板文件", Toast.LENGTH_SHORT).show();
            }

            reader = new PdfReader(is);
            bos = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, bos);

            // 使用中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(bf);

            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            for (String fieldName : fields.getFields().keySet()) {
                fields.setFieldProperty(fieldName, "textfont", bf, null);  // 设置中文字体
                fields.setFieldProperty(fieldName, "textsize", 12f, null);  // 设置字体大小为12
            }
            fillData(fields, data()); // 渲染数据

            // 必须调用这个，否则文档不会生成
            ps.setFormFlattening(true);
            ps.close();

            // 获取当前日期作为文件夹名称
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

            // 获取当前时间戳作为文件名
            String timeStamp = String.valueOf(System.currentTimeMillis());

            // 构建你要保存的目录路径
            File dir = new File(externalStorage, "MFBdata/AirdropCard");
            if (!dir.exists()) {
                dir.mkdirs();  // 创建日期文件夹
            }

            // 生成 PDF 文件的路径
            pdfFilePath = dir.getAbsolutePath() + "/" + timeStamp + ".pdf";

            // 写入 PDF 文件
            fos = new FileOutputStream(pdfFilePath);
            fos.write(bos.toByteArray());

            Log.d("airdrop", "PDF 生成成功: " + pdfFilePath);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (is != null) {
                is.close();
            }
        }

        return pdfFilePath;  // 返回生成的 PDF 文件路径
    }
    // MyAdapter类
    class MyAdapter extends RecyclerView.Adapter<MyViewHoder> {
        private List<FlyCardAirdrop> displayedNews;

        public MyAdapter(List<FlyCardAirdrop> newsList) {
            this.displayedNews = newsList;
        }

        @NonNull
        @Override
        public MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(getContext(), R.layout.airdrop_item, null);
            return new MyViewHoder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHoder holder, int position) {
            FlyCardAirdrop item = displayedNews.get(position); //  displayedNews 是 List<News>

            holder.date1.setText(item.getDate1());
            holder.task_type1.setText(item.getTask_type1());
            holder.aircraft1.setText(item.getAircraft1());
            holder.captain1.setText(item.getCaptain1());
            holder.airdrop_area1.setText(item.getAirdrop_area1());
            holder.platform_type1.setText(item.getPlatform_type1());
        }

        @Override
        public int getItemCount() {
            return displayedNews.size();
        }

        // 添加新数据的方法
        public void addData(FlyCardAirdrop news) {
            displayedNews.add(news);
            notifyItemInserted(displayedNews.size() - 1); // 通知插入新项
        }
    }


    class MyViewHoder extends RecyclerView.ViewHolder {
        EditText date1;
        EditText task_type1;
        EditText aircraft1;
        EditText captain1;
        EditText airdrop_area1;
        EditText platform_type1;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            date1 = itemView.findViewById(R.id.date1); // 单位
            task_type1 = itemView.findViewById(R.id.task_type1);           // 日期
            aircraft1 = itemView.findViewById(R.id.aircraft1); // 任务类型或名称
            captain1 = itemView.findViewById(R.id.captain1);   // 飞机
            airdrop_area1 = itemView.findViewById(R.id.airdrop_area1);     // 机长副驾驶
            platform_type1 = itemView.findViewById(R.id.platform_type1); // 空投场名称
        }
    }
    /**
     * 填充模板中的数据
     */
    public  void fillData(AcroFields fields, Map<String, String> data) {
        try {
            for (String key : data.keySet()) {
                String value = data.get(key);
                // 为字段赋值,注意字段名称是区分大小写的
                fields.setField(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 添加预览PDF的方法
    public void previewPDF(Context context, String pdfFilePath) {
        File pdfFile = new File(pdfFilePath);  // 传入最新生成的文件路径
        if (pdfFile.exists()) {
            Uri pdfUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", pdfFile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(pdfUri, "application/pdf");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(context, "没有找到可以打开 PDF 的应用", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "PDF 文件不存在，请先生成 PDF", Toast.LENGTH_SHORT).show();
        }
    }
}